<!-- 系统设置 -->
<template>
    <div class="sys_tabs">

        <div class="sys_title">
            <div class="title">{{ titleConvert(tabs_value, 'zh') }}</div>
            <div class="txt">{{ titleConvert(tabs_value, 'en') }}</div>
        </div>
        <div class="sys_tabbox">
            <div :class="['tabsbtn', tabs_value === 'stock' ? 'selected' : '']" @click="tabs_click('stock')">股票配置</div>
            <div :class="['tabsbtn', tabs_value === 'lever' ? 'selected' : '']" @click="tabs_click('lever')">杠杆配置</div>
            <div :class="['tabsbtn', tabs_value === 'email' ? 'selected' : '']" @click="tabs_click('email')">邮箱配置</div>
            <div :class="['tabsbtn', tabs_value === 'system' ? 'selected' : '']" @click="tabs_click('system')">系统配置</div>

        </div>

        <div class="sys_content" v-loading="content_loading">
            <div class="ztitle">
                <div class="title">变量标题</div>
                <div class="title">变量值</div>
            </div>
            <div class="sys_stock" v-if="tabs_value === 'stock'">
                <div v-for="(val, key, index) in stockList" :key="key" :class="index % 2 === 0 ? 'bg-gray' : 'bg-white'">
                    <label style="display: inline-block; width: 250px;"> {{ stockMap[key] || key }}</label>
                    <!-- boolean 类型字段 -->
                    <el-switch v-if="val === true || val === false || val === 'true' || val === 'false'"
                        v-model="stockList[key]" :active-value="true" :inactive-value="false" />

                    <!-- 时间字段 -->
                    <el-time-picker size="mini" v-else-if="isTimeField(key, val)" v-model="stockList[key]"
                        placeholder="选择时间" value-format="HH:mm:ss" />

                    <!-- 文本 -->
                    <el-input v-else size="mini" v-model="stockList[key]" style="width: 200px;" />
                </div>
                <div class="fbtnsys">
                    <el-button class="black-button" size="mini" plain @click="upd_data('stock')"
                        :loading="xg_loading">确认修改</el-button>
                    <el-button icon="el-icon-refresh" size="mini" class="white-button" :loading="cz_loading"
                        @click="resetForm('stock')">重置</el-button>
                </div>
            </div>

            <div class="sys_lever" v-if="tabs_value === 'lever'">
                <div class="beishu" style="display: flex;">
                    <label style="display: inline-block; width: 250px;">杠杆倍数</label>
                    <div>
                        <div v-for="(item, index) in leverList.leverage_multiples" :key="index"
                            style="margin-bottom: 10px; display: flex; gap: 10px; align-items: center;">
                            <el-input placeholder="键值" type="number" v-model="leverList.leverage_multiples[index]"
                                size="small" style="width: 150px" />
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeItem(index)" />
                        </div>
                        <el-button type="primary" class="leverbtns green-button" icon="el-icon-plus" size="mini"
                            @click="addItem">
                            Append
                        </el-button>
                    </div>



                    <!-- <pre style="margin-top: 20px;">绑定值：{{ leverList.leverage_multiples }}</pre> -->
                </div>
                <div class="switch_on">
                    <label style="display: inline-block; width: 250px;">杠杆开关</label>
                    <el-switch v-model="leverList.leverage_switch" :active-value="true" :inactive-value="false" />
                </div>
                <div class="beishu">
                    <label style="display: inline-block; width: 250px;">杠杆爆仓指数</label>
                    <el-input size="mini" v-model="leverList.leverage_liquidation_threshold" type="number"
                        style="width: 200px;" />
                </div>
                <div class="fbtnsys">
                    <el-button class="black-button" size="mini" plain @click="upd_data('lever')"
                        :loading="xg_loading">确认修改</el-button>
                    <el-button icon="el-icon-refresh" size="mini" class="white-button" :loading="cz_loading"
                        @click="resetForm('lever')">重置</el-button>
                </div>
            </div>

            <div class="sys_email" v-if="tabs_value === 'email'">
                <div v-for="(val, key, index) in emailList" :key="key" :class="index % 2 === 0 ? 'bg-gray' : 'bg-white'">
                    <label style="display: inline-block; width: 250px;"> {{ emailMap[key] || key }}</label>
                    <el-input size="mini" v-model="emailList[key]" style="width: 200px;" />
                </div>
                <div class="fbtnsys">
                    <el-button class="black-button" size="mini" plain @click="upd_data('email')"
                        :loading="xg_loading">确认修改</el-button>
                    <el-button icon="el-icon-refresh" size="mini" class="white-button" :loading="cz_loading"
                        @click="resetForm('email')">重置</el-button>
                </div>
            </div>

            <div class="sys_system" v-if="tabs_value === 'system'">
                <div v-for="(val, key, index) in systemList" :key="key" :class="index % 2 === 0 ? 'bg-gray' : 'bg-white'"
                    style="padding: 6px;">
                    <!-- 嵌套对象递归 -->
                    <div v-if="isObject(val)" class="sys1">
                        <div class="sys11">{{ fieldMap[key] || key }}</div>
                        <!-- 递归渲染子对象 -->
                        <div class="bnduwqgdbyiwq2">
                            <div v-for="(subVal, subKey) in val" :key="subKey">
                                <!-- 如果还是对象，继续嵌套 -->
                                <div v-if="isObject(subVal)">
                                    <div style="font-weight: bold;">{{ fieldMap[subKey] || subKey }}</div>
                                    <div v-for="(deepVal, deepKey) in subVal" :key="deepKey">

                                        <label style="display: inline-block; width: 250px;">{{ fieldMap[deepKey] || deepKey
                                        }}</label>

                                        <el-switch v-if="isBoolean(deepVal)" v-model="subVal[deepKey]" active-value="true"
                                            inactive-value="false" />
                                        <el-time-picker size="mini" v-else-if="isTimeField(deepKey, deepVal)"
                                            v-model="subVal[deepKey]" placeholder="选择时间" value-format="HH:mm:ss" />
                                        <el-input v-else size="mini" v-model="subVal[deepKey]" style="width: 200px;" />
                                    </div>
                                </div>

                                <!-- 不是对象 -->
                                <div v-else class="sysbushiduix">
                                    <label style="display: inline-block; width: 150px;">{{ fieldMap[subKey] || subKey
                                    }}</label>
                                    <el-switch v-if="isBoolean(subVal)" v-model="val[subKey]" active-value="true"
                                        inactive-value="false" />
                                    <el-time-picker size="mini" v-else-if="isTimeField(subKey, subVal)"
                                        v-model="val[subKey]" placeholder="选择时间" value-format="HH:mm" />
                                    <el-input v-else size="mini" v-model="val[subKey]" style="width: 200px;" />
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 最外层普通字段 -->
                    <div v-else style="display: flex; align-items: center;">
                        <label style="display: inline-block; width: 250px;">{{ fieldMap[key] || key }}</label>
                        <el-input v-if="key === 'blocked_ips'" size="mini" v-model="blockedIpsStr" style="width: 300px;"
                            placeholder="多个IP用英文逗号分隔" @input="updateBlockedIps" />
                        <el-switch v-else-if="isBoolean(val)" v-model="systemList[key]" active-value="true"
                            inactive-value="false" />
                        <el-time-picker size="mini" v-else-if="isTimeField(key, val)" v-model="systemList[key]"
                            placeholder="选择时间" value-format="HH:mm:ss" />
                        <el-input v-else size="mini" v-model="systemList[key]" style="width: 200px;" />


                    </div>

                </div>
                <div class="fbtnsys">
                    <el-button class="black-button" size="mini" plain @click="upd_data('system')"
                        :loading="xg_loading">确认修改</el-button>
                    <el-button icon="el-icon-refresh" size="mini" class="white-button" :loading="cz_loading"
                        @click="resetForm('system')">重置</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { system_settings_list, system_settings_editing } from "@/utils/api";
export default {
    name: "systemConfiguration",
    data() {
        return {
            content_loading: false,
            cz_loading: false,
            xg_loading: false,
            stockList: [],
            leverList: [],
            emailList: [],
            systemList: [],
            tabs_value: 'stock',
            stockMap: {
                stock_market_open_switch: '股票市场开关',
                stock_morning_open_time: '上午开市时间',
                stock_morning_close_time: '上午闭市时间',
                stock_afternoon_open_time: '下午开市时间',
                stock_afternoon_close_time: '下午闭市时间',
                stock_trade_fee: '交易手续费',
                stock_closing_fee: '收盘费',
                stock_overnight_fee: '隔夜费',
                stock_lot_size: '最小交易单位',
                stock_withdrawal_fee: '提现手续费',
                stock_min_withdrawal_amount: '最低提现金额',
                stock_pre_market_switch: '盘前交易开关',
                stock_pre_market_start_time: '盘前开始时间',
                stock_pre_market_end_time: '盘前结束时间',
                stock_post_market_switch: '盘后交易开关',
                stock_post_market_start_time: '盘后开始时间',
                stock_post_market_end_time: '盘后结束时间'
            },
            emailMap: {
                sender_email: '发件人邮箱',
                smtp_auth_type: 'SMTP认证类型',
                smtp_method: 'SMTP协议类型',
                smtp_password: 'SMTP密码',
                smtp_port: 'SMTP端口号',
                smtp_server: 'SMTP服务器地址',
                smtp_username: 'SMTP用户名',
            },
            fieldMap: {
                site_name: '网站名称',
                record_number: '备案号',
                version: '版本号',
                timezone: '时区',
                blocked_ips: '被封禁IP',
                backend: '后台语言设置',
                frontend: '前台语言设置',
                language_settings: '语言设置',
                admin_fixed_page: '管理后台默认页',
                customer_service_url: '客服链接',
                trading_system: '交易系统标识',
                deposit_account: '充值账户',
                deposit_bank_card: '银行卡号',
                deposit_bank_type: '银行类型',
                deposit_refresh_seconds: '充值刷新时间',
                withdraw_refresh_seconds: '提现刷新时间',
                account_settings: '账户设置',
                start_time: '折扣开始时间',
                end_time: '折扣结束时间',
                discount_purchase_open_time: '限时折扣开放时间',
                about_us: '关于我们',
                data_update_time: '数据更新时间',
                app_home_bar_chart_data: 'App首页柱状图数据',
                "-3%~-0%": '跌幅 0%~3%',
                "-5%~-3%": '跌幅 3%~5%',
                "-7%~-5%": '跌幅 5%~7%',
                "-7%_below": '跌幅 >7%',
                "0%~3%": '涨幅 0%~3%',
                "3%~5%": '涨幅 3%~5%',
                "5%~7%": '涨幅 5%~7%',
                "7%_above": '涨幅 >7%',
                flat: '平盘'
            },
            blockedIpsStr: '',

        }
    },
    mounted() {
        this.get_data('stock')
    },
    computed: {

    },
    methods: {
        resetForm(type) {
            this.get_data(type)
        },
        updateBlockedIps() {
            this.systemList.blocked_ips = this.blockedIpsStr
                .split(',')
                .map(ip => ip.trim())
                .filter(ip => ip);
        },
        addItem() {
            this.leverList.leverage_multiples.push(1)
        },
        isObject(val) {
            return val && typeof val === 'object' && !Array.isArray(val);
        },
        isBoolean(val) {
            return val === true || val === false || val === 'true' || val === 'false';
        },
        isTimeField(key, val) {
            return typeof val === 'string' && /^\d{2}:\d{2}(:\d{2})?$/.test(val);
        },
        removeItem(index) {
            this.leverList.leverage_multiples.splice(index, 1)
        },
        // isTimeField(key, val) {
        //     return typeof val === 'string' && key.toLowerCase().includes('time');
        // },
        isNumericField(val) {
            // 字符串里只要是数字（带小数也算），就返回 true
            if (typeof val === 'number') return true;
            if (typeof val === 'string') {
                // 去掉空格后是否是数字
                return val.trim() !== '' && !isNaN(Number(val));
            }
            return false;
        },
        // 文字转换
        titleConvert(title, lang) {
            const map = {
                stock: {
                    zh: '股票配置',
                    en: 'Stock Allocation'
                },
                lever: {
                    zh: '杠杆配置',
                    en: 'Leverage Configuration'
                },
                email: {
                    zh: '邮箱配置',
                    en: 'Email Configuration'
                },
                system: {
                    zh: '系统配置',
                    en: 'System Configuration'
                }
            };
            return map[title]?.[lang] || title;
        },
        // 设置标签页
        tabs_click(type) {
            this.tabs_value = type
            this.get_data(type)
        },
        // 查询
        async get_data(type) {

            if (!type) return

            this.content_loading = true
            let params = `/${type}`

            try {
                const res = await system_settings_list(params);
                if (res.data && res.data.code == "200") {
                    console.log(res, '系统设置' + type);
                    if (type === 'stock') this.stockList = res.data.data.value
                    if (type === 'lever') {
                        this.leverList = res.data.data.value
                        console.log(this.leverList, ' this.leverList ');
                    }
                    if (type === 'email') this.emailList = res.data.data.value
                    if (type === 'system') {
                        this.systemList = res.data.data.value

                        this.blockedIpsStr = res.data.data.value.blocked_ips.join(', ');
                    }
                } else {
                    this.$message.error(res?.data?.msg || "获取数据失败");
                }
            } catch (err) {
                console.error("获取数据失败:", err);
                this.$message.error("请求出错，请稍后再试");
            } finally {
                this.content_loading = false
            }
        },
        // 更新
        async upd_data(type) {
            this.xg_loading = true;






            try {
                let data = {}

                if (type === 'stock') {


                    data = this.stockList


                } else if (type === 'lever') {


                    data.leverage_liquidation_threshold = Number(this.leverList.leverage_liquidation_threshold)
                    data.leverage_switch = this.leverList.leverage_switch
                    data.leverage_multiples = this.leverList.leverage_multiples.map(item => {
                        const num = Number(item);
                        return isNaN(num) ? null : num;
                    });



                } else if (type === 'email') {


                    data = this.emailList

                    if (data.smtp_port) {
                        data.smtp_port = Number(data.smtp_port)
                    }


                } else if (type === 'system') {


                    data = this.systemList


                    if (data.app_home_bar_chart_data) {

                        for (const key in data.app_home_bar_chart_data) {
                            data.app_home_bar_chart_data[key] = Number(data.app_home_bar_chart_data[key]);
                        }
                    }

                    if (data.account_settings.deposit_refresh_seconds) {
                        data.account_settings.deposit_refresh_seconds = Number(data.account_settings.deposit_refresh_seconds)
                    }
                    if (data.account_settings.withdraw_refresh_seconds) {
                        data.account_settings.withdraw_refresh_seconds = Number(data.account_settings.withdraw_refresh_seconds)
                    }
                    console.log(data, 'this.emasystemil');
                }

                const response = await system_settings_editing(type, data);

                if (response.data && response.data.code == "200") {
                    this.$message.success(response.data.message);

                    this.get_data(type);
                } else {
                    this.$message.warning(response?.data?.msg || "操作失败");
                }
            } catch (err) {
                console.error("更新失败:", err);
                this.$message.error("请求出错，请稍后再试");
            } finally {
                this.xg_loading = false;
            }
        },
    },

}
</script>

<style lang="less">
.sys_tabs {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;

    .fbtnsys {
        padding-left: 250px;
        padding-top: 15px;
    }

    .sys_title {
        background-color: #e8edf0;
        padding: 15px;

        .title {
            font-weight: 700;
            font-size: 16px;
        }

        .txt {
            font-size: 14px;
        }
    }

    .sys_tabbox {
        display: flex;
        padding-left: 15px;
        background-color: #e8edf0;

        .tabsbtn {
            height: 35px;
            padding: 15px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 14px;
            cursor: pointer;
            margin: 0 5px;
            background-color: #d8e0e6;
            color: #95a5a6;
        }

        .selected {
            background-color: #ffffff;
            color: #333;
        }
    }

    .sys_content {
        padding: 15px 23px;
        background-color: #fff;
        max-height: calc(100vh - 210px);
        overflow: auto;

        .sys_stock {}
    }

    .ztitle {
        display: flex;

        .title {
            min-width: 250px;
            padding: 15px 0;
            font-size: 14px;
            font-weight: 700;
        }
    }

    .el-input {
        min-width: 300px;
    }

    .bg-gray {
        background-color: #f9f9f9;
        padding: 5px 0;
        font-size: 14px;
    }

    .bg-white {
        background-color: #ffffff;
        padding: 5px 0;
        font-size: 14px;

    }

    .sys_lever {

        .beishu {
            background-color: #f9f9f9;
            padding: 15px 5px;
        }

        .switch_on {
            padding: 15px 5px;
        }

        .leverbtns {
            padding: 7px 8px;
            border-radius: 0;
        }

        .leverbtns * {
            font-weight: 700;
            // font-size: 14px;
        }
    }

    .sys1 {

        display: flex;

        .sys11 {
            font-weight: bold;
            width: 250px;
        }
    }

    .sysbushiduix {
        display: flex;
        align-items: center;
        padding: 5px 0;
    }
}
</style>